import TodoList, { ITodoData } from './TodoList'
    ; ((doc) => {

        const oInput: HTMLInputElement = doc.querySelector('input')
        const oBtn: HTMLElement = doc.querySelector('button')
        const oTodoList: HTMLLIElement = doc.querySelector('.todo-list')


        /**
         * 操作数据
         * 增加 addTodo
         * 删除 removeTodo
         * 改变状态 toggleComplete
         */
        const todoList = TodoList.create(oTodoList)

        const init = (): void => {
            bindEvent()
        }
        function bindEvent() {
            oBtn.addEventListener('click', handleAddBtnClick, false)
            oTodoList.addEventListener('click', handleTodoListClick, false)
        }
        function handleAddBtnClick() {
            const val: string = oInput.value.trim()
            if (!val.length) return
            todoList.addItem(<ITodoData>{
                id: Math.random(),
                content: val,
                completed: true
            })
        }
        function handleTodoListClick(e: MouseEvent) {
            const tar = e.target as HTMLLIElement
            const tarName = tar.tagName.toLowerCase()

            if (['input', 'button'].includes(tarName)) {
                const id: number = Number(tar.dataset.id)
                switch (tarName) {
                    case 'input':
                        todoList.toggleComplete(id, tar)
                        break;
                    case 'button':
                        todoList.removeItem(id, tar)
                        break;
                    default:
                        break
                }
            }
        }
        init()
    })(document)